package com.example.zhanghehe.myapplication

import android.opengl.GLES20
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import javax.microedition.khronos.opengles.GL

class Triangle:Graph {

    private var vertexBuffer: FloatBuffer

    private var mProgram: Int

    init{
        val bb=ByteBuffer.allocateDirect(
            triangleCoords.size*4
        )
        bb.order(ByteOrder.nativeOrder())

        vertexBuffer=bb.asFloatBuffer()
        vertexBuffer.put(triangleCoords)
        vertexBuffer.position(0)

        val vertexShader=MyGLRender.loadShader(
            GLES20.GL_VERTEX_SHADER, vertexShaderCode
        )
        val fragmentShader=MyGLRender.loadShader(
            GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode
        )

        mProgram=GLES20.glCreateProgram()
        GLES20.glAttachShader(mProgram,vertexShader)
        GLES20.glAttachShader(mProgram,fragmentShader)
        GLES20.glLinkProgram(mProgram)


    }

    private var mPositionHandle: Int = 0

    private var mColorHandle: Int = 0

    private var mMVPMatrixHandle: Int = 0

    override fun draw(matrix: FloatArray) {
        GLES20.glUseProgram(mProgram)

        mPositionHandle=GLES20.glGetAttribLocation(mProgram,"vPosition")
        GLES20.glEnableVertexAttribArray(mPositionHandle)

        GLES20.glVertexAttribPointer(
            mPositionHandle, COORDS_PER_VERTEX,
            GLES20.GL_FLOAT,false,
            vertexStride,vertexBuffer
        )

        mColorHandle=GLES20.glGetUniformLocation(mProgram,"vColor")
        GLES20.glUniform4fv(mColorHandle,1,color,0)

        mMVPMatrixHandle=GLES20.glGetUniformLocation(mProgram,"uMVPMatrix")
        MyGLRender.checkGlError("glGetUniformLocation")

        GLES20.glUniformMatrix4fv(mMVPMatrixHandle,1,false,matrix,0)
        MyGLRender.checkGlError("glUniformMatrix4fv")

        GLES20.glDrawArrays(GLES20.GL_TRIANGLES,0, vertexCount)
        GLES20.glDisableVertexAttribArray(mPositionHandle)
    }


    companion object {
        val vertexShaderCode=
                """
                    uniform mat4 uMVPMatrix;
                    attribute vec4 vPosition;
                    void  main(){
                        gl_Position=uMVPMatrix*vPosition;
                    }
                """.trimIndent()

        val fragmentShaderCode=
                """
                    precision mediump float;
                    uniform vec4 vColor;
                    void main(){
                        gl_FragColor=vColor;
                    }
                """.trimIndent()

        val COORDS_PER_VERTEX=3
        val triangleCoords= floatArrayOf(
            0.0f,0.6222f,0.0f,
            -0.5f,-0.311f,0.0f,
            0.5f,-0.311f,0.0f
        )
        val vertexCount= triangleCoords.size/ COORDS_PER_VERTEX
        val vertexStride= COORDS_PER_VERTEX*4
        val color= floatArrayOf(0.63f,0.769f,0.222f,0.0f)
    }

}
